﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Workflow_Core_API.Persisted;
using WorkflowCore.Interface;
using WorkflowCore.Models;
using WorkflowCore.Service.Dto.Fundamentals;
using WorkflowCore.Service.Manger;
using WorkflowCore.Service.Persisted;

namespace WorkflowCore.Service.Strps
{
    /// <summary>
    /// 初始化步骤
    /// //添加一些审计记录，判断是否发布，没发布等待发布，若发布则执行下一个步骤
    /// </summary>
    public class StartStep : StepBody
    {
        private readonly IWorkflowManger manger;
        private readonly WorkflowCoreDbcontext _db;

        public StartStep(IWorkflowManger _manger, WorkflowCoreDbcontext db)
        {
            manger = _manger;
            _db = db;
        }

        public override ExecutionResult Run(IStepExecutionContext context)
        {
            var workflowLaunchInput = JsonConvert.DeserializeObject<WorkflowLaunchInput>(
                 JsonConvert.SerializeObject(context.Workflow.Data));

            if (!context.ExecutionPointer.EventPublished)
            {
                var auditList = _db.persistedWorkflowAuditor.Count(p => p.WorkflowId == context.Workflow.Id);
                if (auditList > 1) // 如果审批记录大于1，则一定是重新发起
                {
                    manger.AddAudit(context, OperateType.Start, WorkFlowAuditStatus.UnAudited, null
                        , workflowLaunchInput.UserId, workflowLaunchInput.UserName);

                    // 修改业务流程实例
                    var instance =
                        _db.persistedWorkflowInstance.FirstOrDefault(p => p.WorkflowInstanceId == context.Workflow.Id);
                    instance.CurrentStepId = nameof(StartStep);
                    instance.CurrentStepName = nameof(StartStep);
                    instance.CurrentAuditUserIds = workflowLaunchInput.UserId.ToString();
                    instance.CurrentAuditUsers = workflowLaunchInput.UserName;
                    instance.Status = WorkflowInstanceStatus.WorkflowStart;
                    _db.SaveChanges();

                    // 等待重新发起
                    Console.WriteLine($"等待{workflowLaunchInput.UserName}重新发起");
                    return ExecutionResult.WaitForEvent(WorkflowConst.WaitForRestartEvent, context.Workflow.Id,
                        DateTime.Now);
                }
            }

            // 正常发起
            manger.AddAudit(context, OperateType.Start, WorkFlowAuditStatus.Pass, DateTime.Now
                , workflowLaunchInput.UserId, workflowLaunchInput.UserName);

            return ExecutionResult.Next();
        }
    }
}
